<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="clickExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="clickShowAddDialog">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格 -->
      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column min-width="100" label="序号" type="index" :index="indexMethod" sortable="" />
          <el-table-column min-width="100" label="姓名" prop="username" sortable="" />
          <el-table-column min-width="100" label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img v-imgerror class="staff" :src="row.staffPhoto || defaultImg" alt="" @click="handleImgClick(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column min-width="120" label="工号" prop="workNumber" sortable="" />
          <el-table-column min-width="100" :formatter="formatterEmployment" label="聘用形式" prop="formOfEmployment" sortable="" />
          <el-table-column min-width="100" label="部门" prop="departmentName" sortable="" />
          <el-table-column min-width="100" label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column min-width="100" label="账户状态" prop="enableState" sortable="">
            <template #default="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button :disabled="row.mobile === 13800000002" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="page"
          :page-sizes="[6,12, 18, 24]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <add-employee :show-dialog.sync="showDialog" />

      <el-dialog width="300px" title="图片二维码" :visible="showCodeDialog" :before-close="closeDialog">
        <div style="text-align: center;">
          <canvas ref="imgCanvas" />
        </div>
      </el-dialog>

      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

    </div>
  </div>
</template>

<script>
import { reqDelEmployee, reqGetEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'

export default {
  name: 'Employees',

  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: 1, // 当前页
      size: 6, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      defaultImg: 'https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2026506810,1548839222&fm=26&gp=0.jpg',
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    editRole(id) {
      this.userId = id
      this.showRoleDialog = true
    },
    async getEmployeeList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },

    formatterEmployment(row, column, cellValue, index) {
      // 正式
      // console.log(row.forOfEmployment)  // 1
      // console.log(EmployeeEnum.hireType)  // [{id: 1,..},{id:2,...}]
      const obj = EmployeeEnum.hireType.find(item => item.id === row.formOfEmployment)
      return obj ? obj.value : '未知'
    },
    delEmployee(id) {
      this.$confirm('mua~  你确认要进行删除操作吗？', '温馨提示').then(async() => {
        // 发送删除请求
        await reqDelEmployee(id)
        // 如果删除的是当前页的最后一条，当前页 -1
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    clickShowAddDialog() {
      this.showDialog = true
    },
    async  clickExport() {
      // 注意： 如果导出的是当前页，那么数据，this.list即可
      // 但是我们一般导出的是全部的数据，需要请求到所有的数据
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.formatJson(rows, headersArr, headersRelations)

      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          // 二纬数组 [ [], [], [] ]
          data: dataArr, // 具体数据 必填
          filename: '学生信息表', // 非必填
          autoWidth: true, // 是否开启单元格
          bookType: 'xlsx' // 类型格式
        })
      })
    },

    formatJson(rows, headersArr, headersRelations) {
      const resultArr = rows.map(item => {
        const arr = []
        // 根据headersArr 取到数据
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          // 如果是时间相关，需要格式化处理
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? formatDate(value) : '暂无'
          }
          // 如果是聘用形式，需要处理
          if (englishKey === 'forOfEmployment') {
            const result = EmployeeEnum.hireType.find(obj => obj.id === value)
            value = result ? result.value : '未知'
          }
          arr.push(value)
        })
        return arr
      })
      return resultArr
    },
    handleImgClick(url) {
      if (!url || url === '') return
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.imgCanvas, url)
      })
    },
    closeDialog() {
      this.showCodeDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
